/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.iec.edp.caf.security.core.details;

import io.iec.edp.caf.security.core.GrantedAuthority;
import io.iec.edp.caf.security.core.UserDetailsSource;
import io.iec.edp.caf.security.core.UserState;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * This is {@link PersonalUser}.
 *
 * @author zhangtianyi
 * @since 1.0.0
 */
@SuppressWarnings("unused")
@Slf4j
@Builder
public class PersonalUser implements User {

    private static final long serialVersionUID = -4737116536165380590L;

    private final String userId;

    private final String userCode;

    private final String username;

    private final String secret;

    private final String mail;

    private final String phone;

    private final String avatar;

    private final String currentTenantId;

    private String defaultTenantId;

    private final List<String> tenantIds;

    private final String nickName;

    private final String fullName;

    private String fullNameEn;

    private final String firstName;

    private final String middleName;

    private final String lastName;

    private final String title;

    private Locale locale;

    private String customizedLocaleString;

    private String timezone;

    private Date accountExpiresAt;

    private Date secretExpiresAt;

    private Date lastUpdate;

    private UserState state;

    private Map<String, String> externalAttributes;

    private UserDetailsSource userDetailsSource;

    private Collection<? extends GrantedAuthority> authorities;

    /**
     * important
     * CafSecurityPostAuthenticationFilter.shouldNotFilter may read it
     */
    @Getter
    private final boolean boundLocalUser;

    @Setter
    @Getter
    private boolean weakerPassword;


    @Override
    public String getId() {
        return userId;
    }

    @Override
    public String getCode() {
        return userCode;
    }

    @Override
    public String getName() {
        return username;
    }

    @Override
    public Optional<String> getFullNameEn() {
        return Optional.ofNullable(fullNameEn);
    }

    @Override
    public void setFullNameEn(String fullNameEn) {
        this.fullNameEn = fullNameEn;
    }


    @Override
    public UserTypeEnum getType() {
        return UserTypeEnum.PERSON;
    }

    @Override
    public Optional<String> getTimezone() {
        return Optional.empty();
    }

    @Override
    public Optional<String> getCustomizedLocaleString() {
        return Optional.ofNullable(customizedLocaleString);
    }

    @Override
    public boolean isAccountNonExpired() {
        return accountExpiresAt == null || new Date().before(accountExpiresAt);
    }

    @Override
    public boolean isAccountNonLocked() {
        return state == null || !state.equals(UserState.LOCKED);
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return secretExpiresAt == null || new Date().before(secretExpiresAt);
    }

    @Override
    public boolean isEnabled() {
        return true;
    }

    @Override
    public UserDetailsSource getUserDetailsSource() {
        return userDetailsSource;
    }

    @Override
    public Optional<String> getExternalAttributeAsString(String attributeName) {
        return externalAttributes != null
                ? Optional.ofNullable(externalAttributes.get(attributeName))
                : Optional.empty();
    }

    @Override
    public void updateExternalAttribute(Map<String, String> attributes) {
        externalAttributes.putAll(attributes);
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return authorities;
    }

    @Override
    public PersonalUser toPersonalUser() {
        return this;
    }

    @Override
    public ServiceUser toServiceUser() throws UserTypeMismatchException {
        throw new UserTypeMismatchException(UserTypeEnum.PERSON.toString());
    }

    public boolean secretMatches(String secret) {
        if (secret == null || secret.isEmpty()) {
            log.warn("User's secret is not found.");
            return false;
        }
        return this.secret.equals(secret);
    }

    public Optional<String> getMail() {
        return Optional.ofNullable(mail);
    }

    public Optional<String> getPhone() {
        return Optional.ofNullable(phone);
    }

    public Optional<String> getAvatar() {
        return Optional.ofNullable(avatar);
    }

    public Optional<String> getCurrentTenantId() {
        return Optional.ofNullable(currentTenantId);
    }

    public Optional<String> getDefaultTenantId() {
        return Optional.ofNullable(defaultTenantId);
    }

    public Optional<List<String>> getTenantIds() {
        return Optional.ofNullable(tenantIds);
    }


    public Optional<String> getNickName() {
        return (nickName == null || nickName.isEmpty()) ? Optional.ofNullable(firstName) : Optional.of(nickName);
    }

    public Optional<String> getFullName() {
        if (fullName == null || fullName.isEmpty()) {
            Stream<String> names = Stream.of(firstName, middleName, lastName)
                    .filter(Objects::nonNull)
                    .map(Objects::toString);

            // Chinese Name
            if (this.locale != null && this.locale.getLanguage().equals("zh-cn")) {
                return Optional.of(names.collect(Collectors.joining("")));
            }
            return Optional.of(names.collect(Collectors.joining(" ")));
        }
        return Optional.of(fullName);
    }

    public Optional<String> getFirstName() {
        return Optional.ofNullable(firstName);
    }

    public Optional<String> getMiddleName() {
        return Optional.ofNullable(middleName);
    }

    public Optional<String> getLastName() {
        return Optional.ofNullable(lastName);
    }

    public Optional<String> getTitle() {
        return Optional.ofNullable(title);
    }

    public Optional<Locale> getLocale() {
        return Optional.ofNullable(locale);
    }

    @Override
    public void setCustomizedLocaleString(String customizedLocaleString) {
        this.customizedLocaleString = customizedLocaleString;
    }

    public Optional<Date> getLastUpdate() {
        return Optional.ofNullable(lastUpdate);
    }

}
